package com.gomokult.servlet.matching;

import java.io.*;
import com.gomokult.entity.MatchingRequest;
import com.gomokult.service.impl.MatchingServiceImpl;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet("/servlet/RequestMatchingServlet")
public class RequestMatchingServlet extends HttpServlet {
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		MatchingServiceImpl matchingQueues = MatchingServiceImpl.getSingleton();

		int userID = Integer.parseInt(request.getParameter("userID"));
		long timestamp = Long.parseLong(request.getParameter("timestamp"));
		MatchingRequest matchingRequest = new MatchingRequest(userID, timestamp);

		int level = Integer.parseInt(request.getParameter("level"));
		matchingQueues.clearRequest(userID);
		matchingQueues.requestMatching(matchingRequest, Math.max(0, Math.min(7, level)));

		String matchedUserID = "?#0";
		while ((matchedUserID = matchingQueues.pollMatchingResult(userID)).equals("?#0"));
		out.print(matchedUserID);
	}
}
